<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Helper {

    public static function generateHashString($str) {
        return substr(hash('sha256', $str),-20);
    }
    
    public static function deleteImage($filename, $save_dir) {
        $file_path = $save_dir.$filename;
        if (file_exists($file_path) && file_exists($save_dir)) {
            unlink($file_path);
        }
    }

    public static function saveFile($filename, $tmp_dir, $save_dir) {
        $from_path = $tmp_dir .'/'.$filename;
        $to_path   = $save_dir.'/'.$filename;
        if (file_exists($from_path) && file_exists($save_dir)) {
            if (copy($from_path , $to_path)) {
                unlink($from_path);
            }
        }
    }
    
    public static function convArray($array = array(), $index, $val)
    {
        if(empty($array)) {
            return array();   
        }
        
        foreach($array as $values) {
            $rtn[$values[$index]] = $values[$val];
        }
        return $rtn;
    }

    public static function getUploadData() {
        $files = array();
        foreach (array_keys($_FILES) as $name ) {
            if (is_array($_FILES[$name]["name"])) {
                $count = 0;
                foreach (array_keys($_FILES[$name]["name"]) as $key) {
                    if (!empty($_FILES[$name]["name"][$key])) {
                        $count++;
                        $files[$name.$count]["name"]     = $_FILES[$name]["name"][$key];
                        $files[$name.$count]["type"]     = $_FILES[$name]["type"][$key];
                        $files[$name.$count]["size"]     = $_FILES[$name]["size"][$key];
                        $files[$name.$count]["tmp_name"] = $_FILES[$name]["tmp_name"][$key];
                        $files[$name.$count]["error"]    = $_FILES[$name]["error"][$key];
                    }
                }
            } else {
                $files[$name] = $_FILES[$name];
            }
        }
        $_FILES = $files;
        return $files;
    }

    public static function delTree($dir) {
        $files = array_diff(scandir($dir), array('.','..'));
        foreach ($files as $file) {
            (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file");
        }
        rmdir($dir);
// 		return rmdir($dir);
    }

    public static function pager_tpl(&$page_display)
    {
        $str = $page_display;
        $str = str_replace('<strong>', '<li><strong>', $str);
        $str = str_replace('</strong>', '</strong></li>', $str);
        $str = str_replace('<a', '<li', $str);
        $str = str_replace('</a>', '</li>', $str);
        $str = str_replace('href="/', 'onclick="pager(', $str);
        $str = str_replace('">', ');">', $str);
        return $str;
    }
}
